#!/bin/sh
# ScolioSim Helper Installer for macOS. Built by build-mac.mjs into ScolioSim-Helper-Mac.zip.
#
# The same installation as the line for Terminal (https://scoliosim.com/segment/helper-install.sh),
# with windows instead of text, as on Windows: a window to start, one while it works, one at the end.
# It installs for this user only, without administrator rights, into
#   ~/Library/Application Support/ScolioSim/Helper
# The app is not signed by Apple: the first time, macOS sends the doctor to System Settings,
# Privacy & Security, "Open Anyway". What it installs is written here, not downloaded and opened,
# so nothing else asks again.
# The curly quotes are text for the doctor, and the ~ is shown, not expanded
# shellcheck disable=SC1111,SC2088
set -u
PATH=/usr/bin:/bin:/usr/sbin:/sbin
export PATH

CONTENTS=$(cd "$(dirname "$0")/.." && pwd)
ICON="$CONTENTS/Resources/scoliosim.icns"
SCRIPT=${SCOLIOSIM_INSTALL_SCRIPT:-https://scoliosim.com/segment/helper-install.sh}
PORT=41789
LOG="$HOME/Library/Logs/ScolioSim Helper Install.log"
LOG_SHOWN="~/Library/Logs/ScolioSim Helper Install.log"

# The first language of this Mac (an app opened from the Finder has no LANG)
FIRST=$(defaults read -g AppleLanguages 2>/dev/null | sed -n '2p' | tr -d ' ",')
unset LC_ALL LC_MESSAGES
case "$FIRST" in es*) ES=1; LANG=es_ES.UTF-8 ;; *) ES=; LANG=en_US.UTF-8 ;; esac
export LANG

# tr "English" "Español"
tr_() { if [ -n "$ES" ]; then printf '%s' "$2"; else printf '%s' "$1"; fi; }

# A window: ask "text" "button" ... ; the last button is the default. Prints the button pressed.
ask() {
  osascript - "$@" "$ICON" <<'EOF' 2>/dev/null
on run argv
  set n to count of argv
  set msg to item 1 of argv
  set icn to item n of argv
  set btns to items 2 thru (n - 1) of argv
  activate
  try
    set r to display dialog msg buttons btns default button (count of btns) with title "ScolioSim Helper" with icon (POSIX file icn)
  on error number e
    if e is -128 then return ""
    -- Without its icon, if the icon cannot be read
    set r to display dialog msg buttons btns default button (count of btns) with title "ScolioSim Helper" with icon note
  end try
  return button returned of r
end run
EOF
}

# The window shown while it works, apart from this script; it closes when the work is done
WORKING=
working() {
  osascript - "$1" "$2" "$ICON" <<'EOF' >/dev/null 2>&1 &
on run argv
  activate
  try
    display dialog (item 1 of argv) buttons {item 2 of argv} default button 1 with title "ScolioSim Helper" with icon (POSIX file (item 3 of argv)) giving up after 1800
  on error number e
    if e is not -128 then display dialog (item 1 of argv) buttons {item 2 of argv} default button 1 with title "ScolioSim Helper" with icon note giving up after 1800
  end try
end run
EOF
  WORKING=$!
}
done_working() { [ -n "$WORKING" ] && kill "$WORKING" 2>/dev/null; WORKING=; }
trap done_working EXIT

# 1. Welcome
INSTALL=$(tr_ "Install" "Instalar")
GO=$(ask "$(tr_ "ScolioSim Helper

It lets the ScolioSim web app segment a CT with TotalSegmentator on this Mac. The CT never leaves the computer.

It installs for you alone, without administrator rights, in a minute or two (it downloads its own small Python, about 30 MB). TotalSegmentator itself is installed afterwards, from ScolioSim, when you ask." "ScolioSim Helper

Permite a la aplicación web ScolioSim segmentar un TAC con TotalSegmentator en este Mac. El TAC no sale del ordenador.

Se instala solo para usted, sin permisos de administrador, en uno o dos minutos (descarga su propio Python pequeño, unos 30 MB). TotalSegmentator se instala después, desde ScolioSim, cuando usted lo pida.")" \
  "$(tr_ "Cancel" "Cancelar")" "$INSTALL")
[ "$GO" = "$INSTALL" ] || exit 0

# 2. The installation, with its window
mkdir -p "$HOME/Library/Logs"
working "$(tr_ "Installing the ScolioSim helper…

This takes a minute or two. This window closes by itself when it is done." "Instalando el asistente de ScolioSim…

Tarda uno o dos minutos. Esta ventana se cierra sola al terminar.")" "$(tr_ "Hide" "Ocultar")"

TMP=$(mktemp -d "${TMPDIR:-/tmp}/scoliosim-installer.XXXXXX")
if curl -fsSL --retry 3 --retry-delay 5 "$SCRIPT" -o "$TMP/helper-install.sh" 2>"$LOG"; then
  sh "$TMP/helper-install.sh" >"$LOG" 2>&1 </dev/null
  CODE=$?
else
  CODE=1
  tr_ "The installer could not be downloaded from scoliosim.com." "No se pudo descargar el instalador de scoliosim.com." >>"$LOG"
fi
rm -rf "$TMP"
done_working

# 3. The end
CLOSE=$(tr_ "Close" "Cerrar")
if [ "$CODE" -eq 0 ] && curl -s -m 3 "http://127.0.0.1:$PORT/status" >/dev/null 2>&1; then
  ask "$(tr_ "The ScolioSim helper is installed and running.

Go back to ScolioSim in the browser (Chrome or Edge) and click “Connect to the helper”: it guides the rest. This installer can go to the Trash; to update the helper later, open it again." "El asistente de ScolioSim está instalado y en marcha.

Vuelva a ScolioSim en el navegador (Chrome o Edge) y pulse «Conectar con el asistente»: le guiará en lo demás. Este instalador puede ir a la Papelera; para poner al día el asistente más adelante, vuelva a abrirlo.")" \
    "$(tr_ "Done" "Terminar")" >/dev/null
elif [ "$CODE" -eq 0 ]; then
  ask "$(tr_ "The ScolioSim helper is installed, but did not answer yet.

In ScolioSim, click “Already installed? Start it”." "El asistente de ScolioSim está instalado, pero aún no responde.

En ScolioSim, pulse «¿Ya está instalado? Póngalo en marcha».")" \
    "$(tr_ "Done" "Terminar")" >/dev/null
else
  # What went wrong is the last line the installation wrote
  WHY=$(grep -v '^[[:space:]]*$' "$LOG" 2>/dev/null | tail -n 1)
  DETAILS=$(tr_ "Show the details" "Ver los detalles")
  PRESSED=$(ask "$(tr_ "The ScolioSim helper could not be installed.

$WHY

Check the internet connection and open this installer again. The details are in $LOG_SHOWN." "No se pudo instalar el asistente de ScolioSim.

$WHY

Compruebe la conexión a internet y vuelva a abrir este instalador. Los detalles están en $LOG_SHOWN.")" \
    "$DETAILS" "$CLOSE")
  [ "$PRESSED" = "$DETAILS" ] && open -e "$LOG"
  exit 1
fi
exit 0
